/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package SensorView;


import javax.microedition.io.Connector;
import javax.microedition.sensor.*;
import java.io.IOException;
import sUtils.*;

public class SensorData extends Object {

    private SensorConnection sensorConnection;
    private String url;
    private String name;
    private String val;
    private Data dt[];
    boolean dirty;

    public SensorData( String _name, String _url ) {
            sensorConnection = null;
            url = _url;
            val = _url;
            name = _name;
            dirty = false;
    }

    public void connect( DataListener listener )
    {
      try {
            sensorConnection = (SensorConnection) Connector.open(url);
            sensorConnection.setDataListener(listener, 1);
             val = name + ": ";
        } catch (IOException e)
        {
            e.printStackTrace();
            val = name + Lang.word(" not found"," nicht gefunden");
        }
    }

    public void updateValue()
    {
        if (dirty) {   
        StringBuffer s = new StringBuffer(50);

        s.append(name);
        s.append("=");
        for ( int i=0; i<dt.length; i++ ) {
            if (i>0) s.append(";"); 
            switch ( dt[i].getChannelInfo().getDataType() )
            {
                case ChannelInfo.TYPE_DOUBLE: s.append( dt[i].getDoubleValues()[0] ); break;
                case ChannelInfo.TYPE_OBJECT: s.append( "object" ); break;
                default: s.append( dt[i].getIntValues()[0] ); break;
            }
        }

        val = s.toString();
        dirty = false;
        s=null;
        
        }
    }

    public void setData( Data[] data ) {
        dt = data; dirty = true;
    }

    public SensorConnection getConn() { return sensorConnection; }
    public String value() { return val; }
    public String getName() { return name; }

    public void close() {
        if (sensorConnection != null) {
            try {
                sensorConnection.removeDataListener();
                sensorConnection.close();
                url = "";
            } catch (IOException e) {
                e.printStackTrace();
            }
            sensorConnection = null;
        }
    }
}
